package com.onepiece.requestproxy.factory;

import java.util.List;
import java.util.Set;

import com.onepiece.requestproxy.annotation.IRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class RequestBeanFactory implements BeanFactoryPostProcessor {

	private static final Logger logger = LoggerFactory
			.getLogger(RequestBeanFactory.class);

	private List<String> packagesToScan;

	public void postProcessBeanFactory(
			ConfigurableListableBeanFactory beanFactory) throws BeansException {
		try {
			for (String pack : packagesToScan) {
				if (StringUtils.isNotBlank(pack)) {
					if (logger.isDebugEnabled()) {
						logger.debug("scan package have : {}",pack);
					}
					Set<Class<?>> classSet = PackagesToScanUtil
							.getClasses(pack);
					for (Class<?> requestClass : classSet) {
						if (requestClass.isAnnotationPresent(IRequest.class)) {
							// 单独加载一个接口的代理类
							ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
							proxyFactoryBean.setBeanFactory(beanFactory);
							proxyFactoryBean
									.setInterfaces(new Class[] { requestClass });
							proxyFactoryBean
									.setInterceptorNames(new String[] { "requestHandler" });
							String beanName = getClassName(requestClass);
							if (!beanFactory.containsBean(beanName)) {
								beanFactory.registerSingleton(beanName,
										proxyFactoryBean.getObject());
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getClassName(Class<?> requestClass) {
		IRequest iRequest = requestClass.getAnnotation(IRequest.class);
		if (StringUtils.isNotEmpty(iRequest.value())) {
			return iRequest.value();
		}
		String name = requestClass.getSimpleName();
		name = name.trim();
		if (name.length() >= 2) {
			return name.substring(1, 2).toLowerCase() + name.substring(2);
		} else {
			return name.toLowerCase();
		}

	}

	public List<String> getPackagesToScan() {
		return packagesToScan;
	}

	public void setPackagesToScan(List<String> packagesToScan) {
		this.packagesToScan = packagesToScan;
	}

}
